<?php

class Teacher_IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        ////        $teacher = new Teacher_Model_Teacher;
        ////        $teacher->assignIdentifier('1030');
        ////        $teacher->condition_state = '0';
        ////        $teacher->save();
        //        Doctrine_Query::create()
        //        ->update('Teacher_Model_Teacher')
        //        ->set('condition_state=?',0)->execute();
        $condition =  $this->_getParam('select_state',0);
        $form = new Teacher_Form_Teacher();
        $condition_clone = clone $form->getElement('condition_state');
        $condition_clone->setValue($condition);

        $this->view->select_state =  $condition_clone->setName('select_state');

        $request = $this->getRequest();
        $q = Doctrine_Query::create()
        ->select('a.username, a.name, a.sex, b.name AS title_name, b.sort AS title_sort')
        ->from('Teacher_Model_TeacherView a')
        ->leftJoin('a.Teacher_Model_TeacherTitle b')
        ->where('a.condition_state=?',$condition)
        ->orderby('b.sort, a.name');

        $this->view->teacher_list = $q->fetchArray();

        $this->view->teacher = $form;

        //$user = new Default_Model_DbTable_AclRoles();
        //$tt = $user->find('級任教師')->current();

        //		$ss = $tt->findDependentRowset('Default_Model_DbTable_Groups');
        //		echo '<pre>';
        //		var_dump($ss->toArray());
        //		var_dump($tt);
    }

    public function setAction()
    {

        $request = $this->getRequest();
        if ($request->isPost()){
            $form = new Teacher_Form_Teacher();
            if($form->isValid($request->getParams())){

                $teacher = new Teacher_Model_Teacher();
                $user = new Default_Model_Users();
                // 檢查是否為新增 user
                $row = $user->getTable()->findOneBy('username', $request->getParam('old_username'));

                $isNew = false;
                if ($row){
                    $row->username = $request->getParam('username');
                    $row->name = $request->getParam('name');
                    $row->save();
                }
                else {
                    $user = new Default_Model_Users();
                    $password = $this->_helper->passOperate(Bootstrap::$config['sfs']['teacher']['default_password']);
                    $user->username = $request->getParam('username');
                    $user->password = $password;
                    $user->name = $request->getParam('name');
                    $user->save();
                    $isNew = true;
                }

                if (!$isNew)
                $teacher->assignIdentifier($request->getParam('username'));

                $teacher->FromArray($form->getValues());
                $teacher->save();


                if ($request->getParam('condition_state')==0) {
                    // TODO Doctrine_Record 1.2 bug
                    // condition_state 等於 0 時無法存入
                    // 先暫時 Doctrine_Query 儲存
                    Doctrine_Query::create()
                    ->update('Teacher_Model_Teacher')
                    ->set('condition_state=?',0)
                    ->where('username=?',$request->getParam('username'))
                    ->execute();

                    // 加入職稱群組
                    $teacherTitle = new Teacher_Model_TeacherTitle();
                    $row = $teacherTitle->getTable()->find($request->getParam('current_title_sn'));
                    $role_id = $row->name;
                    $arr = array();
                    $arr['username']= $request->getParam('username');
                    $arr['role_id'] = $role_id;
                    $groups = new Default_Model_Groups();
                    $groups->updateRole($arr,'title');

                    // 加入處室群組
                    $schoolRoom = new School_Model_SchoolRoom();
                    $row = $schoolRoom->getTable()->find($request->getParam('current_office_id'));
                    $roleId = $row->name;
                    $arr = array();
                    $arr['username']= $request->getParam('username');
                    $arr['role_id'] = $roleId;
                    $groups = new Default_Model_Groups();
                    $groups->updateRole($arr,'room');
                    // 加入教師群組
                    $arr['role_id'] = "Teacher";
                    $groups->updateRole($arr,'Default');
                    // 加入 教師學期任職記錄
                    $q  = Doctrine_Query::create()
                    ->select('sn')
                    ->from('Semester_Model_SemesterTeacher')
                    ->where('year=?', $this->view->Semester['year'])
                    ->andWhere('semester=?',  $this->view->Semester['semester'])
                    ->andWhere('teacher_id=?',$request->getParam('username'));
                    $res = $q->fetchOne();
                    $semesterTeacher = new Semester_Model_SemesterTeacher();
                    $update_sn = Teacher_Model_Teacher::getSnById($request->getParam('username'));
                    if ($res)
                    $semesterTeacher->assignIdentifier($res['sn']);
                    $semesterTeacher->year= $this->view->Semester['year'];
                    $semesterTeacher->semester = $this->view->Semester['semester'];
                    $semesterTeacher->teacher_id = $request->getParam('username');
                    $semesterTeacher->kind_sn = $request->getParam('current_kind_sn');
                    $semesterTeacher->title_sn = $request->getParam('current_title_sn');
                    $semesterTeacher->office_id = $request->getParam('current_office_id');
                    $semesterTeacher->condition_state = $request->getParam('condition_state');
                    $semesterTeacher->update_sn = $update_sn;
                    $semesterTeacher->save();

                }
                else {
                    // 如果已離職則刪除所有群組
                    $groups = new Default_Model_Groups();
                    $username = $request->getParam('username');
                    $q = Doctrine_Query::create()
                    ->delete('Default_Model_Groups')
                    ->where('username=?',$username);

                    $q->execute();
                }

                $this->_helper->json(true);

            }
            else {
                $this->_helper->json($form->getMessages());
            }
        }
    }


    /**
     *  upload photo image
     * @return unknown_type
     */
    function uploadphotoAction()
    {
        if($this->_request->isPost()){
            $formData = $this->_request->getPost();

            $file_path  = $this->_helper->getStorePath('photo/teacher');
            $username = $this->_request->getParam('username');
            $adapter = new Zend_File_Transfer_Adapter_Http();
            $adapter->setDestination($file_path)
            ->addValidator('Extension',false,'jpg,png');
            $photo = $adapter->getFileInfo('photo');
            $temp_arr = explode(".",$photo['photo']['name']);
            $ss = time();
            $file_name =  $ss. '.'.end($temp_arr);
            $photo_name = $ss.'_'.end($temp_arr);
            $adapter->addFilter('Rename', array(
            //$photo['photo']['tmp_name'],
			'target'=>$file_path . $file_name,
			'overwrite'=>true
            ));

            if ($adapter->receive('photo'))
            {

                $teacher = new Teacher_Model_Teacher();
                $row = $teacher->getTable()->findOneBy('username', $username);

                if ($row->photo_name){
                    $tt = str_replace("_",".",$row->photo_name);
                    if (is_file($file_path.$tt)) {
                        unlink($file_path.$tt);
                        unlink($file_path.'tmb_'.$tt);
                    }
                }

                $q = Doctrine_Query::create()
                ->update('Teacher_Model_Teacher')
                ->set('photo_name','?',$photo_name)
                ->where('username=?', $username);
                $q->execute();
                // 縮圖
                $thumb = new Sfs_Image_Thumb($file_path . $file_name);
                $thumb->resize(135);
                $thumb->save($file_path.'tmb_'.$file_name, 100);
                echo $photo_name;
            }
        }

        exit;

    }

    /**
     * 下載照片檔
     *
     */
    public function teacherimgAction()
    {
        $ss = $this->_request->getParam('photo');
        $temp = explode("_",$ss);

        $photo = 'tmb_'.$temp[0].'.'.$temp[1];
        $file_path  = $this->_helper->getStorePath('photo/teacher');

        if (file_exists($file_path.$photo)) {
            $this->_helper->downloadFile($photo,'photo/teacher');
        }

    }

    /**
     * Delete a teacher's photo
     * @return unknown_type
     */

    public function delimageAction()
    {
        $this->getHelper('layout')->disableLayout();
        $this->getHelper('ViewRenderer')->setNorender();
        $username = $this->_request->getParam('username');
        $file_path  = $this->_helper->getStorePath('photo/teacher');
        if (file_exists($file_path.$username))
        unlink($file_path.$username);
        echo $username;
    }

    /**
     * 刪除教師
     * @return unknown_type
     */
    public function deleteAction()
    {
        $username = $this->_getParam('id','');
        // 刪除 User 資料
        $q = Doctrine_Query::create()
        ->delete('Default_Model_Users')
        ->where('username=?', $username);
        $q->execute();

        $this->_helper->json(array('username'=>$username));
    }

    /**
     * 取得一位教師詳細資料
     *  吳俊奇
     資訊組長    陳瑩光
     生活教育組長  王金印
     體衛組長
     */
    public function getteacherAction()
    {
        $username = $this->_request->getParam('username','');
        $f = new Zend_Filter_StripTags();
        $username = $f->filter($username);
        $q = Doctrine_Query::create()
        ->from('Teacher_Model_TeacherView')
        ->where('username=?', $username);
        $res = $q->fetchOne();
        if ($res) {
            $data = $res->toArray();
            $this->_helper->json($data);
        }
        else {
            $this->_helper->json(0);
        }
    }
    /**
     * 檢查代號是否重複
     */
    public function checkuserAction()
    {
        $username = $this->_request->getParam('username','');
        $f = new Zend_Filter_StripTags();
        $username = $f->filter($username);
        $users = new Default_Model_Users();
        if ($row = $users->getTable()->findOneBy('username',$username))
        $this->_helper->json($row->name);
        else {
            $this->_helper->json(false);
        }

    }

}

